<template>
  <div class="auth-wrapper">
    <div class="bg-white auth-wrapper-box">
      <div class="auth-wrapper-box-top">
        <div class="title">CMS管理系统</div>
        <div class="subTitle">登录并开启今天的管理工作</div>
      </div>
      <a-form ref="loginRef" :rules="loginRules" :model="loginForm">
        <a-form-item name="username">
          <a-input
            placeholder="请输入账号"
            size="large"
            :bordered="false"
            v-model:value="loginForm.username"
            class="w-[280px]"
          >
            <template #prefix>
              <i class="iconfont icon-zhanghao text-[#0083ff]"></i>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="password">
          <a-input-password
            placeholder="请输入密码"
            size="large"
            :bordered="false"
            v-model:value="loginForm.password"
            class="w-[280px]"
          >
            <template #prefix>
              <i class="iconfont icon-mima text-[#0083ff]"></i>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item name="code">
          <a-input
            v-model:value="loginForm.code"
            size="large"
            :bordered="false"
            placeholder="请输入验证码"
            :maxlength="6"
            class="w-[280px]"
            @keyup.enter.native="handleSubmit"
          >
            <template #prefix> <i class="iconfont icon-yanzhengma text-[#0083ff]"></i></template>
            <template #suffix>
              <img
                v-if="captcha"
                :src="captcha"
                class="w-[97px] h-[36px] absolute right-0 cursor-pointer"
                @click="setCaptcha"
              />
              <div
                v-else
                class="w-[97px] h-[36px] absolute right-0 cursor-pointer flex items-center justify-center"
                @click="setCaptcha"
              >
                <redo-outlined class="mr-[8px]" />
                <span>重试</span>
              </div>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button
            block
            type="primary"
            size="large"
            :loading="loading"
            @click="handleSubmit"
            class="w-[280px] loginBtn"
          >
            登录
          </a-button>
        </a-form-item>
        <!--
          <a-form-item>
          <div class="grid grid-cols-2 gap-4 w-[280px]">
            <a class="ant-btn ant-btn-block" href="/daily.html" target="_blank"> 日报 </a>
            <RouterLink class="ant-btn ant-btn-block" to="/editor" target="_blank"> 编辑平台 </RouterLink>
          </div>
        </a-form-item>
       -->
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRaw } from 'vue'
import { useRouter, RouterLink } from 'vue-router'
import { message } from 'ant-design-vue'
import useStore from '@/stores'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  permission: { login, loginCode }
} = apis
const { user } = useStore()
console.log('useStore: ', user)
const loginRef = ref()
const loading = ref(false)
const router = useRouter()
const captcha = ref()
interface LoginFormState {
  username: string
  password: string
  code: string
}
const loginForm: LoginFormState = reactive({
  username: '',
  password: '',
  code: ''
})
//密码正则
const pwdReg = /^[\dA-Za-z_!@#$%^&*`~()-+=.]{6,20}$/
const validatePassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    return Promise.reject('请输入密码')
  } else if (!pwdReg.test(value)) {
    return Promise.reject('请输入6-20个字符，可包含英文字母、数字和标点符号（除空格）')
  } else {
    return Promise.resolve()
  }
}
const validateCode = (rule: any, value: any, callback: any) => {
  if (!value) {
    return Promise.reject('请输入验证码')
  } else if (value.length < 6) {
    return Promise.reject('请输入6位验证码')
  } else {
    return Promise.resolve()
  }
}
const loginRules = {
  username: {
    required: true,
    message: '请输入账号',
    trigger: 'blur'
  },
  password: {
    required: true,
    validator: validatePassword,
    trigger: 'blur'
  },
  code: {
    required: true,
    validator: validateCode,
    trigger: 'blur'
  }
}

const setCaptcha = () => {
  loginCode().then((res: any) => {
    captcha.value = 'data:image/png;base64,' + res.code_image
  })
}
setCaptcha()

const handleSubmit = () => {
  loginRef.value.validate().then(() => {
    console.log(toRaw(loginForm), loginForm)
    loading.value = true
    login(loginForm)
      .then((res: any) => {
        console.log(res, 'res')
        storage.set('user', res.data.admin)
        storage.set('token', res.data.token)
        user.token = res.data.token
        user.user = res.data.admin
        message.success('登录成功，正在跳转...！')
        setTimeout(() => {
          loading.value = false
          message.destroy()
          router.replace({ name: 'Index' })
        }, 1500)
      })
      .catch(() => {
        loading.value = false
        setCaptcha()
      })
  })
}
onMounted(() => {
  storage.remove('previewToken')
})
</script>

<style lang="less" scoped>
:deep(.ant-form-item-explain-error) {
  margin-left: 45px;
}
:deep(.ant-input-affix-wrapper > input.ant-input) {
  font-size: 14px;
}
:deep(.ant-input-prefix) {
  margin-right: 18px;
}
.ant-input-affix-wrapper {
  border-bottom: 1px solid #f0f0f0;
}
.auth-wrapper {
  background-image: url('@/assets/icon/background.jpg');
  @apply flex items-center justify-center w-screen h-screen bg-center bg-no-repeat;
  background-size: 100vw 100vh;
  &-box {
    width: 360px;
    min-height: 400px;
    position: absolute;
    right: 22%;
    top: 31%;
    border-radius: 10px;
    padding: 24px 40px;

    &-top {
      text-align: center;
      .title {
        width: 154px;
        height: 28px;
        font-size: 20px;
        color: #000000;
        letter-spacing: 4px;
        margin: 0 auto;
      }
      .subTitle {
        width: 290px;
        font-size: 12px;
        color: #999999;
        font-family: PingFangSC-Regular;
        letter-spacing: 11.6px;
        margin: 6px 0 49px;
      }
    }
    .loginBtn {
      box-shadow: 4px 4px 16px 0px rgba(0, 131, 255, 0.5);
    }
  }
}
</style>
